package fctuc.dei.myTwitter.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.nio.channels.SelectionKey;

import fctuc.dei.myTwitter.com.MT;
import fctuc.dei.myTwitter.com.Message;
import fctuc.dei.myTwitter.com.MessageHandler;

public class SocketThread extends UserConnection implements Runnable{
	private Socket sock;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;

	public SocketThread(Socket s, MessageHandler mh){
		super(mh);
		this.sock = s;
		this.setServerStatus(true);
//		System.out.println("<<< TCP: incoming connection");
	}

	public void run(){

		try{
			ois = new ObjectInputStream(sock.getInputStream());
			oos = new ObjectOutputStream(sock.getOutputStream());
			//envia as mensagens que chegam e invoca o metodo que as vais tratar
			while(receive((Message) ois.readObject()))
				;
		}catch (IOException io){
			//io.printStackTrace();
			terminate();
		}catch (ClassNotFoundException cl){
			//cl.printStackTrace();
			terminate();
		}
	}

	@Override
	public boolean realSend(Message m) {
		//TODO:
		/*
		 * Tenho de ter uma variavel -> cleanExit
		 * E tenho de ter um id para as connections para poder reenviar as mensagens que ficaram pendentes do meu lado
		 */
		try{
			oos.writeObject(m);
//			System.out.println("<<<MSG SENT - "+m.id+" | "+m.type.toString());
		}catch(IOException io){
			io.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public void realTerminate() {
		try {
			if(oos != null)
				oos.close();
			if(ois != null)
				ois.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void noConnectionWarning() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean realSend(Message m, SelectionKey key) {
		// TODO Auto-generated method stub
		return false;
	}


}
